package mms

import com.lucastex.grails.fileuploader.UFile
import grails.converters.JSON

class MultimediaController {

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

    def index = {
        redirect(action: "list", params: params)
    }

    def list = {
        params.max = Math.min(params.max ? params.int('max') : 10, 100)
        [multimediaInstanceList: Multimedia.list(params), multimediaInstanceTotal: Multimedia.count()]
    }
 // 显示媒体
    def full = {
        Multimedia media =   Multimedia.get(params.id) 
        [media : media] 
    }
//  转码
    def transcoding = {
        Multimedia multimediaInstance =   Multimedia.get(params.id) 

        if (multimediaInstance) {
            UFile ufile = UFile.get(multimediaInstance.description)
            def config = grailsApplication.config.fileuploader["movie"]

            def dest =  "${servletContext.getRealPath('/')}upload/${multimediaInstance.path.replace(config.path,'').replace('.'+ufile.extension,'')}.jpg"
            dest = dest.replace('/', '\\')

            def dir = new File(dest.substring(0,dest.lastIndexOf("\\")))
            if (!dir.exists()) {
                dir.mkdirs()
            }

            if (FlvScreenshot.processImg( multimediaInstance.path , dest)) {
                multimediaInstance.preview = dest.replace(servletContext.getRealPath('/'),'/').replace('\\', '/')
                multimediaInstance.save(flush:true)
                log.info "multimediaInstance save."
            }
            log.info  multimediaInstance.path +"=="+ dest
        }
        render("window.close();".encodeAsJs());
        
    }

     // 上传处理页面
    def upload = {
        log.info "Uploaded file with id=${params.ufileId}"
        def json

        if (flash.message) { 
            log.info "${flash.message}"
            render(contentType:"text/plain",text:"{'success': false, 'message':  '${flash.message}'}")
        }else{
            def ufile = UFile.get(params.ufileId.toLong())
            if (ufile) {
                
            def config = grailsApplication.config.fileuploader["movie"]
            if (config.allowedExtensions.contains(ufile.extension)) { // 视频
                 Multimedia media = new Multimedia(description :  params.ufileId,
                        path  : ufile.path,
                        url : createLink(controller: 'download' , id: params.ufileId),
                        preview : "/images/no.png",
                        mediaType : "video");
                
                if (!media.save(flush:true)) { 
                       media.errors.each { msg ->
                            log.info "media save errors ${msg}"
                       } 
                } 
                json = "{'success': true, 'message':  {'id':'${media.id}' , 'description':'${media.description}' , 'size':'${ufile.size}' , 'url' : '${media.preview}'}}"

            }else{

                Multimedia media = new Multimedia(description :  params.ufileId,
                        path  : ufile.path,
                        url : createLink(controller: 'download' , id: params.ufileId),
                        preview : createLink(controller: 'download' , id: params.ufileId),
                        mediaType : "picture");
                
                if (!media.save(flush:true)) { 
                       media.errors.each { msg ->
                            log.info "media save errors ${msg}"
                       } 
                }
                json = "{'success': true, 'message':  {'id':'${media.id}' , 'description':'${media.description}' , 'size':'${ufile.size}' , 'url' : '${media.preview}'}}"

            }
            log.info json
            render(contentType:"text/plain",text: json)
            }
        }
    }

    def create = {
        def multimediaInstance = new Multimedia()
        multimediaInstance.properties = params
        return [multimediaInstance: multimediaInstance]
    }

    def save = {
        def multimediaInstance = new Multimedia(params)
        if (multimediaInstance.save(flush: true)) {
            flash.message = "${message(code: 'default.created.message', args: [message(code: 'multimedia.label', default: 'Multimedia'), multimediaInstance.id])}"
            redirect(action: "show", id: multimediaInstance.id)
        }
        else {
            render(view: "create", model: [multimediaInstance: multimediaInstance])
        }
    }

    def show = {
        def multimediaInstance = Multimedia.get(params.id)
        if (!multimediaInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'multimedia.label', default: 'Multimedia'), params.id])}"
            redirect(action: "list")
        }
        else {
            [multimediaInstance: multimediaInstance]
        }
    }

    def edit = {
        def multimediaInstance = Multimedia.get(params.id)
        if (!multimediaInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'multimedia.label', default: 'Multimedia'), params.id])}"
            redirect(action: "list")
        }
        else {
            return [multimediaInstance: multimediaInstance]
        }
    }

    def update = {
        def multimediaInstance = Multimedia.get(params.id)
        if (multimediaInstance) {
            if (params.version) {
                def version = params.version.toLong()
                if (multimediaInstance.version > version) {
                    
                    multimediaInstance.errors.rejectValue("version", "default.optimistic.locking.failure", [message(code: 'multimedia.label', default: 'Multimedia')] as Object[], "Another user has updated this Multimedia while you were editing")
                    render(view: "edit", model: [multimediaInstance: multimediaInstance])
                    return
                }
            }
            multimediaInstance.properties = params
            if (!multimediaInstance.hasErrors() && multimediaInstance.save(flush: true)) {
                flash.message = "${message(code: 'default.updated.message', args: [message(code: 'multimedia.label', default: 'Multimedia'), multimediaInstance.id])}"
                redirect(action: "show", id: multimediaInstance.id)
            }
            else {
                render(view: "edit", model: [multimediaInstance: multimediaInstance])
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'multimedia.label', default: 'Multimedia'), params.id])}"
            redirect(action: "list")
        }
    }

    def delete = {
        def multimediaInstance = Multimedia.get(params.id)
        if (multimediaInstance) {
            try {
                multimediaInstance.delete(flush: true)
                flash.message = "${message(code: 'default.deleted.message', args: [message(code: 'multimedia.label', default: 'Multimedia'), params.id])}"
                redirect(action: "list")
            }
            catch (org.springframework.dao.DataIntegrityViolationException e) {
                flash.message = "${message(code: 'default.not.deleted.message', args: [message(code: 'multimedia.label', default: 'Multimedia'), params.id])}"
                redirect(action: "show", id: params.id)
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'multimedia.label', default: 'Multimedia'), params.id])}"
            redirect(action: "list")
        }
    }
}
